
#include "LPC24xx.h"
#include "uart.h"
#include "type.h"
#include "debug_settings.h"
#include "motion.h"
#include "sdram.h"


#define NOISE_GATE_IN	(FIO0PIN1 & (1 << 0))
int NOISE_TRIGGERED = 0;

void NOISE_init(void){

	PINMODE0 |= (1 << 18); //Noisegate pin (P0[8] pin 160) has neither a pull up nor pull down.
}

void NOISE_test(void){
	while(1) {
		if(NOISE_GATE_IN) {
			xprintf("Got sound\n");
		}
	}
}

void MOTION_init(void) {

	/**
	 *  Pin 18 -> AD0[0]
	 *
	 */

	MOTION_on();

	PCLKSEL0 |= (1 << 24); // send the the 72Mhz Pclk to the ADC

	//now lets set the A/D Clock.  it must be less than or equal to 4.5Mhz.  Also, high impedance analog input sources work better with a slower clock.
	//There's a divider to be set based on PCLK.  Since our PCLK is 72MHz, we will divide by 16 to get 4.5MHz.
	//We'll write a 15 because the divider adds one.
	AD0CR |= (17 << 8);

	PINSEL1 |= (1 << 14); //select pin 18 to be AD0[0] input
	PINMODE1 |= (2 << 14); //there's no pull up nor pull down resistor on AD0[0]

	AD0CR |= 1; //select AD0[0] (pin 18) to be the pin that we sample on.

	AD0CR |= (1 << 16);//put the A/D in BURST mode.  When we turn the A/D on, it will be constantly sampling AD0.

}

void MOTION_on(void) {
	PCONP |= (1 << 12); //send power to the ADC
	AD0CR |= (1 << 21); //turn on the ADC
}

void MOTION_off(void) {
	AD0CR &= !(1 << 21); //turn off the ADC
	PCONP &= !(1 << 12); // cut power to the ADC
}

void MOTION_test(void) {

	DWORD currStatus;
	DWORD lowestValue;
	DWORD highestValue;
	int count;

	count = 0;
	lowestValue = 0x3FF;
	highestValue= 0x000;



	xprintf("Inside motion sensor test\n");
	while (1) {
		currStatus = AD0GDR;

		//isolate the meaningful bits that represent the voltage level
		currStatus = (currStatus >> 6);
		currStatus &= (0x3FF);
		/*
		if ((currStatus <= 0x120) || currStatus >= 0x200) {
			xprintf("Triggered at currStatus: %03x\n", currStatus);
		}
	*/

		if (currStatus >= 0x006) {
		//if(NOISE_sensed) {
			xprintf("Triggered at currStatus: %03x\n", currStatus);
		}

		/*
		if (currStatus < lowestValue) {
			lowestValue = currStatus;
			xprintf("\nlowestValue: %08x\n\n", lowestValue);
		}
		else if (currStatus > highestValue) {
			highestValue = currStatus;
			xprintf("\nhighestValue: %08x\n\n", highestValue);
		}
		//xprintf("currStatus: %08x\n", currStatus);
		//delay();
		*/
	}

}

int NOISE_sensed(void) {
	DWORD currStatus;
	currStatus = AD0GDR;
	currStatus = (currStatus >> 6);
	currStatus &= (0x3FF);
	if (currStatus >= 0x00a) {
		return 1;
	}

	return 0;
}
